<?php
class PagesController extends AppController {

	var $name = 'Pages';
	var $uses = array('Task', 'Project', 'Time', 'User');
	var $helpers = array('Date');

	function home()
	{
		
		if ($this->Auth->user('role') == 'spectator')
		{
			$this->redirect('/tasks');
		}
		
		$user_projects = $this->Project->get_user_projects_list($this->Auth->user());

		$tasks = (empty($user_projects)) ? array() : $this->Task->find('all', array(
			'conditions' => array(
				'Task.project_id IN (' . implode(',', array_keys($user_projects)) . ')',
				'Performer.id' => $this->Auth->user('id'),
				'OR' => array(
					'Task.modified >' => date("Y-m-d", time() - 60*60*24*3),
					'Task.status <>' => 'closed'
				)
			),
			'order' => $this->get_order_for_tasks()
		));
		
		$times_ =  $this->Time->find('all', array('conditions' => array('Time.status !=' => 'stop', 'user_id' => $this->Auth->user('id'))));

		$times = array();
		foreach($times_ as $time) {
			
			$times[$time['Time']['task_id']] = $time;
			
		}
		
		$this->set('tasks', $tasks);
		$this->set('times', $times);
	}
	
	function report()
	{
		
		if (!empty($this->data['Parametrs']['date_start']) && 
			!empty($this->data['Parametrs']['date_end']) &&
			!empty($this->data['Parametrs']['project']) &&
			!empty($this->data['Parametrs']['user'])
		)
		{	
			$times = $this->Time->find('all', array(
				'conditions' => array(
					'Time.finish >=' => floor(strtotime($this->data['Parametrs']['date_start']) / 60),
					'Time.finish <=' => floor(strtotime($this->data['Parametrs']['date_end']) / 60 ) + 60*24,
					'Time.status' => 'stop',
					'Task.project_id' => $this->data['Parametrs']['project'],
					'Time.user_id' => $this->data['Parametrs']['user'],
				),
				'order' => array('Time.finish' => 'ASC')
			));
			
			$this->set('times', $times);
		}
		
		list($users, $projects) = $this->Project->get_users_projects($this->Auth->user());
		
		$this->set('users', $users);
		$this->set('projects', $projects);
	}
}